#include "Thread_SubBookLoader.h"
#include "DataBaseManager.h"

#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlRecord>
#include <QtCore/QVariant>

#include <QtSql/QSqlError>
#include <QtCore/QDebug>

namespace Jonathan
{

   /**
    * @brief Initializes a new tread that loads sub books for a given book.
    *
    * @param parent Parent object
    */
   Thread_SubBookLoader::Thread_SubBookLoader(QObject *parent) :
       QThread(parent)
   {
   }

   /**
    * @brief Loads the sub books for the given database.
    *
    * @param dbPath Path to database to load books from.
    */
   void Thread_SubBookLoader::LoadBooks (QTreeWidgetItem *bookItem)
   {
      this->m_BookItem = bookItem;
      this->start ();
   }

   /**
    * @brief Performs load on a seperate thread.
    *
    */
   void Thread_SubBookLoader::run ()
   {
      this->m_BookItem->setDisabled (true);
      TreeItem_Book *bookItem = reinterpret_cast<TreeItem_Book*> (this->m_BookItem);
      QSqlDatabase db = DataBaseManager::GetInstance ()->GetDatabase (bookItem->GetBookDbPath ());
      QSqlQuery query = db.exec ("SELECT * FROM book_list ORDER BY BookOrder;");
      while (query.next ())
      {
         QSqlRecord record = query.record ();
         TreeItem_SubBook* subBookItem = new TreeItem_SubBook (record.value ("Name").toString (),
                                                               record.value ("ChapterCount").toInt (), bookItem);
         bookItem->addChild (subBookItem);
      }
      db.close ();
      this->m_BookItem->setDisabled (false);
   }

}
